package com.plant.plants.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;
import com.plant.plants.domain.PlantResponse;
import com.plant.plants.domain.Result;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


public class PlantServices {

    //接收上传文件
    public PlantResponse upload(MultipartFile file) throws Exception {
        PlantResponse plantResponse = plantApi(file);
        return plantResponse;
    }

    //调用百度植物识别API
    private PlantResponse plantApi(MultipartFile file) throws Exception {

        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant";
        // 本地文件路径
        byte[] imgData = file.getBytes();
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");

        String param = "image=" + imgParam;
        String accessToken = AuthService.getAuth();

        String result = com.baidu.ai.aip.utils.HttpUtil.post(url, accessToken, param);
        JSONObject obj = JSON.parseObject(result);
        return JsonObjectToJavaBean(obj);
    }

    //对象转换
    private PlantResponse JsonObjectToJavaBean(JSONObject obj) {
        PlantResponse response = new PlantResponse();
        List<Result> list = new ArrayList<Result>();
        JSONArray jsonArray = obj.getJSONArray("result");
        Result maxResult = new Result();

        for (int i = 0; i < jsonArray.size(); i++) {
            Result entity = new Result();
            entity.setScore(((JSONObject) jsonArray.get(i)).getString("score"));
            entity.setName(((JSONObject) jsonArray.get(i)).getString("name"));

            if (i != 0) {
                Float currentValue = Float.parseFloat(entity.getScore());
                Float lastValue = Float.parseFloat(((JSONObject) jsonArray.get(i - 1)).getString("score"));
                if (currentValue > lastValue) {
                    maxResult = entity;
                }
            } else {
                maxResult = entity;
            }

            list.add(entity);
        }

        response.setDetectorResult(maxResult);
        response.setLog_id(obj.getString("log_id"));
        response.setResult(list);
        return response;
    }
}
